<?php
namespace app\web\controller;

use app\model\Theme; 
use app\model\Share; 
use app\model\Scan; 

class Fans extends Base
{
    public function Fans()
    {
global $_G, $_P;
if (strstr($_SERVER['HTTP_HOST'],".y.yixuan.net")!==false){
    return_msg('请不要使用管理网址操作!');
}

$system = $_G['system'];
$_G['page']['title'] = '粉丝列表 - ' . $system['sysname'];
//load_func('tpl');
$GLOBALS['frames'] = array();
$themeid = intval($_P['themeid']);
if($themeid <= 0){
	$themeid = Theme::getDefaultThemenew();
}
if(empty($themeid)){
	return_msg('还没有创建活动,请联系管理员');
}
$theme = Theme::getThemeById($themeid);
$config = 	Theme::getConfig($themeid);
$id = intval($_P['id']);
$do = 'fans';
$op = !empty($_P['op']) ? $_P['op'] : 'display';

$url = createWebUrl($do,array('op' => 'display','themeid'=>$themeid));
if($op == 'post') {}

if($op == 'display') {
	$themelist = Theme::getAllTheme();

	$pindex = max(1, intval($_P['page']));
	$psize = 20;

    $gsum16 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_fans ) . " as r
    left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
    WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.username='' and r.mobile!='' " ));

	if(!isset($_P['type'])){
		$type = -1;
	}else{
		$type = intval($_P['type']);
	}
	if ($type==5) {
		$sorttxt = ' order by f.scansum desc,f.id desc';
	}elseif ($type==6) {
		$sorttxt = ' order by f.forward desc,f.id desc';
	}elseif ($type==11) {
		$sorttxt = ' order by f.responsum desc,f.id desc';
		// db_update(t_fans, array('responsum' => 0 ));
		if ($pindex==1) {
			db_query("UPDATE ".tablename(t_fans)." SET responsum = responsumxuni WHERE  themeid = '{$themeid}'");
			$record = db_select("SELECT fromuid FROM ".tablename(t_scan)."
		                        WHERE  themeid =" . $themeid );
			foreach ($record as $index => $item) {
		        db_query("UPDATE ".tablename(t_fans)." SET responsum = responsum + 1 WHERE  themeid = '{$themeid}' and uid ={$item['fromuid']}");
			}
		}
	}elseif ($type==4) {
		$sorttxt = ' order by f.tuijian desc,f.id desc';
		if ($pindex==1) {
			db_query("UPDATE ".tablename(t_fans)." SET tuijian = tuijianxuni WHERE  themeid = '{$themeid}'");
			$record = db_select("SELECT fromuid FROM ".tablename(t_record)."
	                            WHERE  themeid =" . $themeid ." and status > 0 and fromuid > 0 order by id desc");
			foreach ($record as $index => $item) {
	        	db_query("UPDATE ".tablename(t_fans)." SET tuijian = tuijian + 1 WHERE  themeid = '{$themeid}' and uid ={$item['fromuid']}");
			}
		}
	}else{
		$sorttxt = ' order by f.id desc';
	}

	$condition = ' f.themeid = :themeid';
	$params[':themeid'] = $themeid;
	if (intval($_P['keyword'])>0) {
		if (strlen($_P['keyword'])==11 || strstr($_P['keyword'],'.')) {
			$condition .= " AND (f.mobile LIKE '%{$_P['keyword']}%' or f.ip LIKE '%{$_P['keyword']}%') ";
		}else{
			$workerurl = $_G['siteroot'] . createWebUrl('scan', array('op' => 'display','themeid'=>$themeid,'keyword'=>$_P['keyword']));
			echo "<script language='javascript' type='text/javascript'>";
			echo "window.location.href='$workerurl';"; 
			echo "</script>";  
			exit;
		}
	}elseif(!empty($_P['keyword'])) {
		$condition .= " AND ( f.ipaddress LIKE '%{$_P['keyword']}%' or f.nickname LIKE '%{$_P['keyword']}%' or f.username LIKE '%{$_P['keyword']}%') ";
	}

	if (empty($_P['createtime']['start'])){
		$starttime =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
		$starttime =  strtotime(date('Y-m-d 00:00:00',$starttime));
	}else{
		$starttime =  strtotime($_P['createtime']['start']);
	}
	$endtime = empty($_P['createtime']['end']) ? strtotime(date('Y-m-d 23:59:59',TIMESTAMP)): strtotime($_P['createtime']['end']) ;
	$condition.= " and f.addtime > '{$starttime}' and f.addtime <= '{$endtime}' ";
	
	
	if ($type==7) {
		$condition.= " and f.status < 1 ";
	}

	if ($type==8) {
		$condition.= " and f.status > 1 ";
	}
    if ($type==9) {
        $condition.= " and f.username='' and f.mobile!='' ";
    }


    if ($type!=10) {
        $condition.= " and (f.mobile!='' or f.nickname!='' or f.avatar!='')  ";
    }else{
        $condition.= " and (f.mobile='' and f.nickname='' and f.avatar='')  ";
    }

	$workerid = $_P['workerid'];
	if(!empty($workerid)){
		$condition.= " and f.workerid = '{$workerid}'  ";
	}


	$total = db_fetchcolumn("SELECT COUNT(*) FROM " . tablename(t_fans) . " as f 
								left join " . tablename ("mc_members") . " as m on f.uid = m.uid 
				WHERE ". $condition, $params);
	
	
	if(checksubmit('export_submit', true)){
		$count = $total;
		$pagesize = ceil($count/5000);
		$header = array(
				'uid' => '会员UID',
				'username' => '姓名', 
				'mobile' => '电话',
				'nickname' => '昵称',
				'nickname2' => '上级',
				'scansum' => '浏览',
				'forward' => '转发',
				'tuijian' => '成交',
				'responsum' => '推荐',  
				'addtime'=>'首次访问',
				'ipaddress' => '网络地区',
				'nickname' => '员工',
		);
        if ($config['isicon'] > 0){
		$header['lightsum'] = '点亮数';
		}
		$keys = array_keys($header);
		$html = "\xEF\xBB\xBF";
		foreach ($header as $li) {
			$html .= $li . "\t ,";
		}
		$html .= "\n";
		for ($j = 1; $j <= $pagesize; $j++) {
			$sql = "SELECT * FROM " . tablename(t_fans) . " as f 
							WHERE " . $condition . $sorttxt ." limit " . ($j - 1) * 5000 . ",5000 ";
			$list = db_select($sql, $params);
			if (!empty($list)) {
				$size = ceil(count($list) / 500);
				for ($i = 0; $i < $size; $i++) {
					$buffer = array_slice($list, $i * 500, 500);
					foreach ($buffer as $row) {
						if($config['isicon'] > 0){
						        if($config['iconnum2'] <= 0){
						            $lightsum = Share::getNumByThemeIdAndOpenidAndStatus($themeid,$row['openid'],1);
						        }else{
						            $lightsum = Scan::getNumByThemeIdAndOpenidAndStatus($themeid,$row['openid'],1);;
						            $lightsum = intval($lightsum/$config['iconnum2']);
						        }
								if($lightsum >= $config['iconnum']){
									$lightsum = $config['iconnum'];
								}
						        $row['lightsum'] =$lightsum;

						}
						if(!empty($row['workerid'])){
							$fans = db_find ( "SELECT w.username,t.name as teamname,s.name as companyname FROM " . tablename ( t_worker ) . " as w
								left join " . tablename ( t_team ) . " as t on w.team = t.id
								left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
								WHERE w.uid = :uid and w.themeid =:themeid
								",array(":themeid"=>$themeid,":uid"=>$row['workerid']));
							$row['workername'] = $fans['username'];
							$row['teamname'] = $fans['teamname'];
							$row['companyname'] = $fans['companyname'];
						}

						$scan = db_find ( "SELECT * FROM " . tablename ( t_scan ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['uid']));
						$fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$scan['fromuid']));
						$row['nickname2'] = $fans['nickname'];
						$row['avatar2'] = $fans['avatar'];
						$row['fromuid2'] = $scan['fromuid'];

						
						$row['addtime']  = date('Y-m-d H:i:s',$row['addtime']);
						unset($info);
						foreach ($keys as $key) {
							$data[] = $row[$key];
						}
						$user[] = implode("\t ,", $data) . "\t ,";
						unset($data);
					}
					$html .= implode("\n", $user);
				}
			}
		}
		header("Content-type:text/csv");
		header("Content-Disposition:attachment; filename=粉丝数据.csv");
		echo $html;
		exit();
	}


	$statustr = array("同城同行","百分百同行","此链接投诉过","此服务器投诉过","黑名单、可能同行","正常","检查员","手工白名单","可能检查员");
	$statustr2 = array("系统锁定","系统锁定","系统锁定","系统锁定","黑名单","正常","","手工白名单","");
	$sql = "SELECT f.* FROM ". tablename(t_fans) . " as f 
			WHERE " . $condition . $sorttxt. " LIMIT ".($pindex - 1) * $psize.','.$psize;
	$list = db_select($sql, $params);

		foreach ($list as $index =>$row){
			if($config['isicon'] > 0){
			        if($config['iconnum2'] <= 0){
			            $lightsum = Share::getNumByThemeIdAndOpenidAndStatus($themeid,$row['openid'],1);
			        }else{
			            $lightsum = Scan::getNumByThemeIdAndOpenidAndStatus($themeid,$row['openid'],1);;
			            $lightsum = intval($lightsum/$config['iconnum2']);
			        }
					if($lightsum >= $config['iconnum']){
						$lightsum = $config['iconnum'];
					}
			        $list[$index]['lightsum'] =$lightsum;

			}
			if(!empty($row['workerid'])){
				$fans = db_find ( "SELECT w.username,t.name as teamname,s.name as companyname FROM " . tablename ( t_worker ) . " as w
					left join " . tablename ( t_team ) . " as t on w.team = t.id
					left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
					WHERE w.uid = :uid and w.themeid =:themeid
					",array(":themeid"=>$themeid,":uid"=>$row['workerid']));
				$list[$index]['workername'] = $fans['username'];
				$list[$index]['teamname'] = $fans['teamname'];
				$list[$index]['companyname'] = $fans['companyname'];
			}

			$scan = db_find ( "SELECT * FROM " . tablename ( t_scan ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['uid']));
			$fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$scan['fromuid']));
			$list[$index]['nickname2'] = $fans['nickname'];
			$list[$index]['avatar2'] = $fans['avatar'];
			$list[$index]['fromuid2'] = $scan['fromuid'];
		}
	
	$pager = pagination($total, $pindex, $psize);
	
}

if($op == 'status') {
	$status = intval($_P['status']);
	$state = db_update(t_fans, array('status' => $status), array('id' => $id));
	return_tips(0, '', 'ajax');
}






if($op == 'delete' && $_G['isSuperAdmin']) {
	$uid = intval($_P['uid']);
	db_delete(t_fans, array('uid' => $uid,'themeid'=>$themeid));
	db_delete(t_relation, array('uid' => $uid,'themeid'=>$themeid));
	db_delete(t_scan, array('uid' => $uid,'themeid'=>$themeid));
	return_tips('删除成功', $url, 'success');
}


$return_clicent = get_defined_vars();
return view('/fans' , $return_clicent);
}
}